package com.hlingsoft.cms.action;

import com.hlingsoft.cms.dao.*;
import com.hlingsoft.cms.entity.*;
import com.hlingsoft.cms.entity.vo.NewsVo;
import com.hlingsoft.cms.util.Common;

import org.apache.commons.fileupload.disk.DiskFileItem;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by selbylei on 2015/5/6.
 */

@Controller
@RequestMapping("/news")
public class NewsAction extends BaseAction {





    private static final int rows = 10;


    /**
     * 发布动态
     *
     * @param appUserId
     * @param content
     * @param request
     * @return
     */
    @RequestMapping(value = "/add.json")
    @ResponseBody
    public Map<String, Object> add(
            @RequestParam(value = "appUserId") long appUserId,
            @RequestParam(value = "content", required = false) String content,
            @RequestParam(value = "tagsId",required = false) Integer tagsId,
            HttpServletRequest request) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        try {
            MultipartFile file = null;

            Date now = new Date();
            News news = new News();

            if (content != null) {
                news.setContent(content);
            }
            news.setAppUserId(appUserId);
            news.setCreateTime(now);
            news.setUpdateTime(now);
            newsDao.addNews(news);

            //如果有图片，添加图片到图片表
            if (tagsId==null) {
                file = ((MultipartHttpServletRequest) request).getFile("file");
                String fileName = file.getOriginalFilename();
                SimpleDateFormat simpleFormat = new SimpleDateFormat("yyyy-MM-dd");
                String dateString = simpleFormat.format(new Date());
                Common.putObject(dateString, fileName, file.getInputStream(),
                        file.getSize());
                String imagePath = "http://icake.oss-cn-hangzhou.aliyuncs.com/news/" + dateString + "/" + fileName;

                CommonsMultipartFile cf= (CommonsMultipartFile)file;
                DiskFileItem fi = (DiskFileItem)cf.getFileItem();
                File f = fi.getStoreLocation();
                BufferedImage sourceImg = ImageIO.read(new FileInputStream(f));


                Image image = new Image();
                image.setWidth(sourceImg.getWidth());
                image.setHeight(sourceImg.getHeight());
                image.setAppUserId(appUserId);
                image.setPath(imagePath);
                image.setType(2);
                image.setCreateTime(now);
                image.setTokeTime(now);
                image.setUpdateTime(now);
                image.setNewsId(news.getId());
                imageDao.addImages(image);
            } else {
                Date cur = new Date();
                Image image = imageDao.getImageByTagsId(tagsId);
                Image image1 = new Image();
                image1.setWidth(image.getWidth());
                image1.setHeight(image.getHeight());
                image1.setAppUserId(image.getAppUserId());
                image1.setNewsId(news.getId());
                image1.setTagsId(image.getTagsId());
                image1.setGoodsId(image.getGoodsId());
                image1.setCommentId(image.getCommentId());
                image1.setPath(image.getPath());
                image1.setType(image.getType());
                image1.setTokeTime(cur);
                image1.setCreateTime(cur);
                image1.setUpdateTime(cur);
                imageDao.addImages(image1);
            }
            resultMap.put("news", news);
            resultMap.put("result", true);
        } catch (Exception e) {
            e.printStackTrace();
            resultMap.put("result", false);
        }
        return resultMap;
    }



    /**
     * 动态列表
     *
     * @param appUserId
     * @param request
     * @return
     */
    @RequestMapping(value = "/list.json")
    @ResponseBody
    public Map<String, Object> add(
            @RequestParam(value = "appUserId") long appUserId,
            @RequestParam(value = "pageNum", defaultValue = "1", required = false) Integer pageNum,
            HttpServletRequest request) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        try {
            //列表
            List<News> newsList = newsDao.getNewsList((pageNum - 1) * rows, rows);
            List<NewsVo> newsVoList = new ArrayList<NewsVo>();
            for (News news : newsList) {
                List<AppUser> likesUserList = new ArrayList<AppUser>();
                List<Likes> likesList = likesDao.getLikesByNewsId2(news.getId());
                for (Likes likes:likesList){
                    AppUser appUser = appUserDao.getUserById(likes.getMyId());
                    if (appUser!=null){
                        likesUserList.add(appUser);
                    }
                }
                AppUser appUser = appUserDao.getUserById(news.getAppUserId());
                //判断活动发布者是否存在
                if (appUser!=null){
                    NewsVo newsVo = new NewsVo();
                    newsVo.setId(news.getId());
                    newsVo.setAppUserId(appUserId);
                    newsVo.setLikesUserList(likesUserList);
                    newsVo.setHeadImageCount(likesUserList.size());
                    newsVo.setContent(news.getContent());

                    List<Image> imageList = imageDao.getImageByNewsId(news.getId());
                    newsVo.setImageList(imageList);
                    Focus focus = focusDao.getFocusByIds(appUserId, news.getAppUserId());
                    if (focus != null) {
                        appUser.setIsFocus(1);
                    } else {
                        appUser.setIsFocus(0);
                    }
                    if (likesDao.getLikesByNewsId(appUserId, news.getId()) != null) {
                        newsVo.setIsLikes(1);
                        appUser.setIsLikes(1);
                    } else {
                        newsVo.setIsLikes(0);
                        appUser.setIsLikes(0);
                    }
                    newsVo.setAppUser(appUser);
                    newsVo.setAuthorization(news.getAuthorization());
                    newsVo.setCreateTime(news.getCreateTime());
                    newsVo.setUpdateTime(news.getUpdateTime());
                    newsVo.setCommentCount(commentDao.getCommentByNewsIdCount(news.getId()));
                    newsVoList.add(newsVo);
                }

            }

            //达人
            List<AppUser> daRenList = appUserDao.getDaRen(0, 4);
            if (pageNum==1){
                resultMap.put("daRenList", daRenList);
            }
            resultMap.put("newsVoList", newsVoList);
            resultMap.put("result", true);
        } catch (Exception e) {
            e.printStackTrace();
            resultMap.put("result", false);
        }
        return resultMap;
    }


    /**
     * 动态详情页面
     *
     * @param appUserId
     * @param newsId
     * @param request
     * @return
     */
    @RequestMapping(value = "/detail.json")
    @ResponseBody
    public Map<String, Object> detail(
            @RequestParam(value = "appUserId") long appUserId,
            @RequestParam(value = "newsId") long newsId,
            HttpServletRequest request) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        try {

            News news = newsDao.getNewsById(newsId);

            if (news!=null) {
                NewsVo newsVo = new NewsVo();
                List<AppUser> likesUserList = new ArrayList<AppUser>();           //点赞人头像
                List<Likes> likesList = likesDao.getLikesByNewsId2(newsId);
                for (Likes likes : likesList) {
                    AppUser appUser = appUserDao.getUserById(likes.getMyId());
                    if (appUser != null) {
                        likesUserList.add(appUser);
                    }
                }

                AppUser appUser = appUserDao.getUserById(news.getAppUserId());
                if (appUser != null) {
                    List<Image> imageList = imageDao.getImageByNewsId(newsId);
                    if (imageList.size() > 0) {
                        newsVo.setImageList(imageList);
                    }
                    newsVo.setId(news.getId());
                    newsVo.setAppUserId(news.getAppUserId());
                    newsVo.setLikesUserList(likesUserList);
                    newsVo.setHeadImageCount(likesUserList.size());
                    newsVo.setContent(news.getContent());

                    Focus focus = focusDao.getFocusByIds(appUserId, news.getAppUserId());
                    if (focus != null) {
                        appUser.setIsFocus(1);
                    } else {
                        appUser.setIsFocus(0);
                    }
                    if (likesDao.getLikesByNewsId(appUserId, news.getId()) != null) {
                        newsVo.setIsLikes(1);
                        appUser.setIsLikes(1);
                    } else {
                        newsVo.setIsLikes(0);
                        appUser.setIsLikes(0);
                    }
                    newsVo.setAppUser(appUserDao.getUserById(news.getAppUserId()));
                    newsVo.setAuthorization(news.getAuthorization());
                    newsVo.setCreateTime(news.getCreateTime());
                    newsVo.setUpdateTime(news.getUpdateTime());

                    List<Comment> commentList2 = commentDao.getCommentByNewsId2(newsId);
                    for (Comment comment : commentList2) {
                        comment.setAppUserImageHead(appUserDao.getUserById(comment.getMyId()).getHeadImage());
                        comment.setMyName(appUserDao.getUserById(comment.getMyId()).getNickname());
                        if (comment.getToId() != 0) {
                            comment.setToName(appUserDao.getUserById(comment.getToId()).getNickname());
                        }
                    }
                    newsVo.setCommentCount(commentDao.getCommentByNewsIdCount(news.getId()));
                    newsVo.setCommentList(commentList2);

                    resultMap.put("newsVo", newsVo);
                    resultMap.put("result", true);
                } else {
                    resultMap.put("msg","news user deleted!");
                    resultMap.put("result",false);
                }

            }else {
                resultMap.put("msg","动态不存在或已被删除!");
                resultMap.put("result",false);
            }
        } catch (Exception e) {
            e.printStackTrace();
            resultMap.put("result", false);
        }
        return resultMap;
    }


    /**
     * 删除动态，同时删除图片，评论
     * @param newsId
     * @param request
     * @return
     */
    @RequestMapping(value = "/delete.json")
    @ResponseBody
    public Map<String, Object> delete(
            @RequestParam(value = "newsId") long newsId,
            HttpServletRequest request) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        try {
             News news = newsDao.getNewsById(newsId);
            if (news!=null){
                //删除相关评论
                List<Comment> commentList=commentDao.getCommentByNewsId2(newsId);
                for (Comment comment:commentList){
                    commentDao.getCommentByNewsId(comment.getId());
                }

                //删除相关点赞
                List<Likes> likesList = likesDao.getLikesByNewsId2(newsId);
                for (Likes likes:likesList){
                    likesDao.deleteLikes(likes.getId());
                }

                //删除活动评论相关消息
                List<CommentMessage> commentMessageList=commentMessageDao.getCommentMessageByNewsId(newsId);
                for (CommentMessage commentMessage:commentMessageList){
                    commentMessage.setAuthorization(0);
                    commentMessageDao.updateCommentMessage(commentMessage);
                }

                //删除活动点赞相关消息
                List<LikesMessage> likesMessageList = likesMessageDao.getLikesMessageByNewsId(newsId);
                for (LikesMessage likesMessage:likesMessageList){
                    likesMessageDao.deleteLikesMessage(likesMessage.getId());
                }

                newsDao.deleteNews(newsId);
                resultMap.put("result",true);
            }else {
                resultMap.put("msg","此动态已被删除!");
                resultMap.put("result",false);
            }
        } catch (Exception e) {
            e.printStackTrace();
            resultMap.put("result", false);
        }
        return resultMap;
    }


    /**
     * 关注人图片
     * @param appUserId
     * @param request
     * @return
     */
    @RequestMapping(value = "/focusNews.json")
    @ResponseBody
    public Map<String, Object> focusNews(
            @RequestParam(value = "appUserId") long appUserId,
            HttpServletRequest request) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        try {
            List<NewsVo> newsVoList = new ArrayList<NewsVo>();
            List<Focus> focusList = focusDao.getAttentionsList(appUserId);
            if (focusList.size()>0){
                for (Focus focus:focusList){
                    List<News> newsList = newsDao.getNewsByAppUserId(focus.getToId());

                    for (News news:newsList){
                        List<AppUser> likesUserList = new ArrayList<AppUser>();

                        //点赞人头像
                        List<Likes> likesList = likesDao.getLikesByNewsId2(news.getId());
                        for (Likes likes:likesList){
                            AppUser appUser = appUserDao.getUserById(likes.getMyId());
                            if (appUser!=null){
                                likesUserList.add(appUser);
                            }
                        }

                        NewsVo newsVo = new NewsVo();
                        newsVo.setId(news.getId());
                        newsVo.setAppUserId(news.getAppUserId());
                        newsVo.setLikesUserList(likesUserList);
                        newsVo.setHeadImageCount(likesUserList.size());
                        newsVo.setContent(news.getContent());

                        List<Image> imageList = imageDao.getImageByNewsId(news.getId());
                        newsVo.setImageList(imageList);
                        AppUser appUser = appUserDao.getUserById(news.getAppUserId());
                        //是否已关注
                        Focus checkFocus = focusDao.getFocusByIds(appUserId, news.getAppUserId());
                        if (checkFocus != null) {
                            appUser.setIsFocus(1);
                        } else {
                            appUser.setIsFocus(0);
                        }
                        //是否可以点赞
                        if (likesDao.getLikesByNewsId(appUserId, news.getId()) != null) {
                            appUser.setIsLikes(1);
                        } else {
                            appUser.setIsLikes(0);
                        }
                        newsVo.setAppUser(appUser);
                        newsVo.setAuthorization(news.getAuthorization());
                        newsVo.setCreateTime(news.getCreateTime());
                        newsVo.setUpdateTime(news.getUpdateTime());
                        newsVoList.add(newsVo);
                    }

                }
                resultMap.put("newsVoList",newsVoList);
                resultMap.put("result",true);
            }else {

                List<News> newsList = newsDao.getNewsByAppUserId(1);

                for (News news : newsList) {
                    List<AppUser> likesUserList = new ArrayList<AppUser>();

                    List<Likes> likesList = likesDao.getLikesByNewsId2(news.getId());
                    for (Likes likes:likesList){
                        AppUser appUser = appUserDao.getUserById(likes.getMyId());
                        if (appUser!=null){
                            likesUserList.add(appUser);
                        }
                   }

                    NewsVo newsVo = new NewsVo();
                    newsVo.setId(news.getId());
                    newsVo.setAppUserId(appUserId);
                    newsVo.setLikesUserList(likesUserList);
                    newsVo.setHeadImageCount(likesUserList.size());
                    newsVo.setContent(news.getContent());

                    List<Image> imageList = imageDao.getImageByNewsId(news.getId());
                    newsVo.setImageList(imageList);
                    AppUser appUser = appUserDao.getUserById(news.getAppUserId());
                    Focus focus = focusDao.getFocusByIds(appUserId, news.getAppUserId());
                    if (focus != null) {
                        appUser.setIsFocus(1);
                    } else {
                        appUser.setIsFocus(0);
                    }
                    if (likesDao.getLikesByNewsId(appUserId, news.getId()) != null) {
                        appUser.setIsLikes(1);
                    } else {
                        appUser.setIsLikes(0);
                    }
                    newsVo.setAppUser(appUser);
                    newsVo.setAuthorization(news.getAuthorization());
                    newsVo.setCreateTime(news.getCreateTime());
                    newsVo.setUpdateTime(news.getUpdateTime());

                    newsVoList.add(newsVo);
                }
                resultMap.put("newsVoList",newsVoList);
                resultMap.put("result",true);

            }
        } catch (Exception e) {
            e.printStackTrace();
            resultMap.put("result", false);
        }
        return resultMap;
    }


}
